<script>
import api from '@/api'
import { mapMutations, mapState } from 'vuex'
import box from '@/mixins/box'

export default {
  name: 'create',
  mixins: [box],
  data() {
    return {
      // 房间id，用于修改房间数据
      id: 0,
      isCreate: {
        type: Boolean,
        default: true,
      },
      // 用户信息
      user: {
        id: 0,
        avatar: '',
        nickname: '',
      },
      // 房间信息
      house: {
        // 房间名
        name: '',
        // 口令
        word_command: '',
        // 房间介绍
        content: '',
        // 房间密码
        room_password: '',
        // 充值开始时间
        start_at: '',
        /*end_at: '',*/
        //  充值金额
        amount: '',
        // 开奖时间
        begin_reward_num: '',
        // 提前开奖人数
        begin_reward_at: '',
      },
      // 开始和结束时间
      /*start_end_at: [],*/
    }
  },
  onLoad(options) {
    this.clearGoods()

    if (options.id) {
      this.id = Number(options.id)
      this.isCreate = false
      this.getHouse()
    } else {
      this.getUser()
    }
  },
  computed: {
    ...mapState('goods', ['goodsList']),
  },
  methods: {
    ...mapMutations('goods', ['deleteGoods', 'clearGoods']),
    async getUser() {
      // 本地获取用户信息
      const avatar = uni.getStorageSync('avatar')
      const nickname = uni.getStorageSync('nickname')
      // 如果获取信息失败，跳转登录页面
      if (!avatar || !nickname) return uni.navigateTo({ url: '/pages/user/wxlogin' })
      this.user = {
        avatar,
        nickname,
      }
    },
    async createHouse() {
      try {
        this.checkData()
        await uni.showLoading()
        const result = await api.welfareHouses.create({
          ...this.house,
          goods_id_arr: this.goodsList.map((item) => item.id).join(','),
        })
        if (result.code === 200) {
          // 创建福利屋成功了
          // this.clearData()
          // await uni.showToast({ title: result.msg })
          setTimeout(() => {
            uni.navigateBack()
          }, 500)
          return
        }
        throw new Error(result.msg)
      } catch (e) {
        await uni.showToast({
          icon: 'none',
          title: e.message,
        })
      } finally {
        await uni.hideLoading()
      }
    },
    async getHouse() {
      await uni.showLoading()
      try {
        const result = await api.welfareHouses.detail(this.id)
        if (result.code === 200) {
          this.house = result.data
          this.user.avatar = result.data.avatar
          this.user.nickname = result.data.nickname
          result.data.prize_list.forEach(item => item.id = item.goods_id)
          this.$store.commit('goods/addGoods', result.data.prize_list)
          return
        }
        throw new Error(result.msg || '获取数据失败')
      } catch (e) {
        await uni.showToast({ icon: 'error', title: e.message })
      } finally {
        await uni.hideLoading()
      }
    },
    clearData() {
      this.clearGoods()
      Object.assign(this.house, {
        name: '',
        word_command: '',
        content: '',
        room_password: '',
        start_at: '',
        /*end_at: '',*/
        amount: '',
        begin_reward_num: '',
        begin_reward_at: '',
      })
    },
    addGoods() {
      this.header('/packageA/welfare/goods', 1, false)
    },
    checkData() {
      const requireArr = ['name', 'word_command', 'amount', 'begin_reward_at', 'start_at']
      for (let k of requireArr) {
        const value = this.house[k]
        if (!value.trim()) {
          throw new Error(`请将必填信息完善`)
        }
      }
      if (!this.goodsList.length) {
        throw new Error('请添加商品')
      }
    },
  },
}
</script>

<template>
  <view class="create-layout">
    <my-header :title="isCreate ? '创建房间' : '修改房间'"></my-header>
    <my-content class="content">
      <scroll-view class="scroll-view" scroll-y="true">
        <view class="user">
          <view class="avatar-bg">
            <image class="avatar" :src="user.avatar"></image>
          </view>
          <text class="username">{{ user.nickname }}</text>
          <text class="house-owner">房主</text>
        </view>
        <view class="house-form">
          <view class="form-item">
            <text class="label require">房间名称</text>
            <input v-model="house.name" class="input" placeholder="请输入房间名称" />
          </view>
          <view class="form-item">
            <text class="label require">房间口令</text>
            <input v-model="house.word_command" class="input" placeholder="用户可通过口令搜索到房间" />
          </view>
          <view class="form-item">
            <text class="label">活动介绍</text>
            <input v-model="house.content" class="input" placeholder="请输入活动活动介绍" />
          </view>
          <view class="form-item">
            <text class="label">房间密码</text>
            <input type="number" v-model="house.room_password" class="input" placeholder="用户需要密码才可参加" />
          </view>
          <view class="form-item">
            <text class="label require">指定消费时间</text>
            <view style="margin-right: 20rpx">
              <uni-datetime-picker
                class="input"
                type="datetime"
                v-model="house.start_at"
              />
            </view>
          </view>
          <view class="form-item">
            <text class="label require">消费总金额</text>
            <input type="number" v-model="house.amount" class="input" placeholder="请输入金额" />
          </view>
          <view class="form-item">
            <text class="label require">开赏时间</text>
            <view style="margin-right: 20rpx">
              <uni-datetime-picker class="input" type="datetime" v-model="house.begin_reward_at" />
            </view>
          </view>
          <view class="form-item">
            <text class="label require">开赏人数</text>
            <input type="number" v-model="house.begin_reward_num" class="input" placeholder="当人数满足时可提前开奖" />
          </view>
          <view class="add-goods">
            <text class="label require">添加商品</text>
            <view class="goods-list">
              <view
                class="goods-item"
                :key="item.id"
                v-for="item in goodsList"
                :style="[useLevelBg('img', item.level_id)]"
              >
                <image class="goods-img" :src="item.image" mode="aspectFit"></image>
                <image class="close" src="/static/images/welfare/ic-close.png" @click="deleteGoods(item.id)"></image>
              </view>
              <view class="goods-item" @click="addGoods"></view>
            </view>
          </view>
        </view>
        <button class="create-house" @click="createHouse">确认{{ isCreate ? '创建' : '修改' }}</button>
        <view style="visibility: hidden"></view>
      </scroll-view>
    </my-content>
  </view>
</template>

<style scoped lang="scss">
.create-layout {
  height: 100vh;
  background-color: #141414;
  box-sizing: border-box;
  padding-bottom: 20rpx;

  .content {
    height: 100%;
    overflow-y: hidden;
    display: flex;
    flex-direction: column;

    .scroll-view {
      overflow-y: hidden;
      height: 100%;
      flex: 1;
    }

    .create-house {
      margin-top: 40rpx;
      width: 610rpx;
      height: 80rpx;
      color: white;
      margin-bottom: 30rpx;
      background-color: transparent;
      background-image: url("https://www.dingxians.cn/upload/user_static/welfare/btn-create.png");
      background-size: 100% 100%;
    }

    .user {
      margin: 30rpx 40rpx;
      display: flex;
      align-items: center;

      .avatar-bg {
        width: 100rpx;
        height: 100rpx;
        background-image: url('https://www.dingxians.cn/upload/user_static/common/icon-border.png');
        background-size: 100% 100%;
        display: flex;
        justify-content: center;
        align-items: center;

        .avatar {
          border-radius: 50%;
          width: 76rpx;
          height: 76rpx;
        }
      }

      .username {
        color: white;
        margin-left: 16rpx;
        font-weight: bold;
        font-size: 32rpx;
      }

      .house-owner {
        margin-left: 16rpx;
        font-size: 22rpx;
        color: #141414;
        padding: 4rpx 8rpx;
        font-weight: bold;
        background-color: #ded000;
      }
    }

    .house-form {
      width: 670rpx;
      margin: 0 auto;
      box-sizing: border-box;
      padding: 1rpx 30rpx 30rpx;
      background-image: url("https://www.dingxians.cn/upload/user_static/welfare/bg-create.png");
      background-size: 100% 100%;

      .require::before {
        content: '*';
        color: red;
        margin-right: 5rpx;
      }

      .label {
        color: white;
      }

      .form-item {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 30rpx;

        .input {
          margin-left: 20rpx;
          flex: 1;
          height: 58rpx;
          color: white;
          text-align: end;

          ::v-deep .uni-date-x {
            background-color: transparent;
          }

          ::v-deep .uni-date-x--border {
            border: none;
          }
        }
      }

      .add-goods {
        margin-top: 30rpx;
        width: 100%;
      }
    }

    .goods-list {
      margin-top: 16rpx;
      display: flex;
      flex-wrap: wrap;

      .goods-item {
        position: relative;
        width: 140rpx;
        height: 140rpx;
        display: flex;
        margin: 5rpx;
        align-items: center;
        justify-content: center;
        background-size: 100% 100%;

        &:last-child {
          border: 1rpx solid #eee;
        }

        .goods-img {
          height: 100rpx;
          width: 100rpx;
        }

        .close {
          z-index: 33;
          width: 24rpx;
          height: 24rpx;
          position: absolute;
          right: 5rpx;
          top: 5rpx;
        }
      }

      .goods-item:last-child {
        background-size: 100% 100%;
        background-image: url('https://www.dingxians.cn/images/welfare/ic-add.png');
      }
    }


  }
}
</style>